package com.dashunzi.yueyutianqi.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;

import com.dashunzi.yueyutianqi.receiver.AutoUpdateReceive;
import com.dashunzi.yueyutianqi.util.HttpCallbackListener;
import com.dashunzi.yueyutianqi.util.HttpUtil;
import com.dashunzi.yueyutianqi.util.Utility;

public class AutoUpdateService extends Service {
    public AutoUpdateService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("---------service方法执行----------");
        //开启子线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                //更新天气
                updateWeather();
            }
        }).start();
        //获取系统的事件管理器
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        //设定时间
        int anHour = 8*60*60 *  1000;//8小时的毫秒数
        //获取elapsedRealTime()返回的是系统从启动到现在的时间。加上设定的时间
        long shijian = SystemClock.elapsedRealtime() + anHour;
        //设定意图，注册一个广播
        Intent i = new Intent(this, AutoUpdateReceive.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, shijian, pi);
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 更新天气信息
     */
    private void updateWeather() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String weatherCode = prefs.getString("weather_code", "");
        String address = "http://www.weather.com.cn/data/cityinfo/" + weatherCode + ".html";
        HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                Utility.handleWeatherResponse(AutoUpdateService.this, response);
            }

            @Override
            public void onError(Exception e) {
                e.printStackTrace();
            }
        });
    }

}
